package com.magold.game.factory;

import java.util.concurrent.TimeoutException;

import org.andengine.engine.camera.SmoothCamera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.opengl.texture.region.ITiledTextureRegion;

import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.magold.context.IContext;
import com.magold.game.MainGameActivity;
import com.magold.io.XMLReader;
import com.magold.logic.ISpriteLogic;
import com.magold.logic.magold.Magold;
import com.magold.logic.polygon.PrimitiveLogic;
import com.magold.logic.polygon.PrimitiveShape;
import com.magold.logic.polygon.RectShape;
import com.magold.texture.TextureFactory;

public class FinishFactory extends BaseLogicFactory {
	private static final String sLoadableElementName = "Finish";
	private static final String PATH = "sprite/finish.png";
	private ITiledTextureRegion mRegion;
	private MainGameActivity mContext;
	
	public FinishFactory(MainGameActivity pContext) {
		super(sLoadableElementName);
		mContext = pContext;
		mRegion = TextureFactory.createRepeatingImage(PATH);
	}

	@Override
	protected ISpriteLogic createSafely(XMLReader pReader) {
		float pWidth = pReader.getFloat("width");
		float pHeight = pReader.getFloat("height");
		PrimitiveShape shape = new RectShape(pWidth, pHeight);
		BodyType type = BodyType.StaticBody;
		
		return new PrimitiveLogic(shape, mRegion.deepCopy(), type) {
			@Override
			protected IContext getContext() {
				return mContext;
			}

			@Override
			public void startCollide(ISpriteLogic pAnthor, Contact pContact) {
				if (mContext.hasFinished()) return;
				mContext.flagFinished();
				
				if (pAnthor instanceof Magold) {
					final Magold m = (Magold) pAnthor;
					mContext.setMenuEnabled(false);
					float duration = m.onFinish();
					Scene gameScene = mContext.getEngine().getScene();
					gameScene.registerUpdateHandler(new TimerHandler(duration, new ITimerCallback() {
						@Override
						public void onTimePassed(TimerHandler pTimerHandler) {
							new TimeoutException().printStackTrace();
							SmoothCamera camera = mContext.getEngine().getCamera();
							camera.clearUpdateHandlers();
							camera.setChaseEntity(m.getSprite());
							camera.setMaxVelocity(300, 300);
							camera.setMaxZoomFactorChange(1f);
							camera.setZoomFactor(3);
							mContext.onFinish();
						}
					}));
				}
			}
		};
	}

}
